<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/9/3
 * Time: 00:36
 */
namespace App\Services;

use App\Repositories\OrderRepository;
use App\Repositories\ThreeApiErrorLogsRepository;
use App\Repositories\UserLevelRepository;
use App\Services\Pay\AlipayService;
use App\Services\Pay\WxpayService;

class MemberUpgradeService extends CommonService
{
    protected $orderRepository;
    protected $userLevelRepository;
    protected $threeApiErrorLogsRepository;

    public function __construct(OrderRepository $orderRepository, UserLevelRepository $userLevelRepository,
                                ThreeApiErrorLogsRepository $threeApiErrorLogsRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->userLevelRepository = $userLevelRepository;
        $this->threeApiErrorLogsRepository = $threeApiErrorLogsRepository;
    }

    /**
     * 微信支付订单
     * @param $userId
     * @param $level
     * @return \Illuminate\Http\JsonResponse
     */
    public function wxpayOrder($userId, $level, $goodsId, $createIp)
    {
        //是否已是服务商
        if ($level == 1) {
            return $this->responseJson(10800);//您已是服务商，无需升级
        }
        //是否已是代言人
        if ($level == 2) {
            return $this->responseJson(10801);//您已是代言人，无需升级
        }
        //是否已是高级会员
        if ($level == 3 && $goodsId == 3) {
            return $this->responseJson(10802);//您已是高级会员，无需升级
        }
        //查找升级等级的价格
        $userLevel = $this->userLevelRepository->byId($goodsId);
        if (empty($userLevel)) {
            return $this->responseJson(10803);//不存在该等级的升级
        }
        $outTradeNo = makeOrderNo();
        $orderName = '开通龙猫管家-' . $userLevel->level_name;
        $payAmount = (config('pay.wxpay.is_debug')) ? 0.01 : $userLevel->amount;
        $createTime = time();
        $orderData = [
            'order_no' => $outTradeNo,
            'order_name' => $orderName,//订单标题
            'user_id' => $userId,
            'goods_id' => $goodsId,
            'firm_type' => 100,//业务类型
            'pay_amount' => $payAmount,//付款金额，单位:元
            'pay_status' => 6000,
            'pay_way' => 2,
            'create_time' => $createTime,
        ];
        //创建订单
        $orderId = $this->orderRepository->insertGetId($orderData);
        if (0 < $orderId) {
            /*** 请填写以下配置信息 ***/
            $mchid = config('pay.wxpay.mchid');
            $appid = config('pay.wxpay.appid');
            $appKey = config('pay.wxpay.app_key');
            $apiKey = config('pay.wxpay.api_key');
            $notifyUrl = config('pay.wxpay.notify_url');
            /*** 配置结束 ***/
            $wxPay = new WxpayService($mchid, $appid, $appKey, $apiKey);
            $orderStr = $wxPay->createAppBizPackage($payAmount, $outTradeNo, $orderName, $notifyUrl, $createTime, $createIp);
            $errorRes = [
                'order_no' => $outTradeNo,
                'error_code' => '',
                'error_msg' => json_encode($orderStr),
                'api_type' => 14
            ];
            $this->threeApiErrorLogsRepository->create($errorRes);
            return $this->responseJson(0, ['pay_info' => $orderStr]);
        } else {
            return $this->responseJson(400);
        }
    }

    /**
     * 支付宝支付订单
     * @param $userId
     * @param $level
     * @return \Illuminate\Http\JsonResponse
     */
    public function alipayOrder($userId, $level, $goodsId)
    {
        //是否已是服务商
        if ($level == 1) {
            return $this->responseJson(10800);//您已是服务商，无需升级
        }
        //是否已是代言人
        if ($level == 2) {
            return $this->responseJson(10801);//您已是代言人，无需升级
        }
        //是否已是高级会员
        if ($level == 3 && $goodsId == 3) {
            return $this->responseJson(10802);//您已是高级会员，无需升级
        }
        //查找升级等级的价格
        $userLevel = $this->userLevelRepository->byId($goodsId);
        if (empty($userLevel)) {
            return $this->responseJson(10803);//不存在该等级的升级
        }
        $outTradeNo = makeOrderNo();
        $orderName = '开通龙猫管家-' . $userLevel->level_name;
        $payAmount = (config('pay.alipay.is_debug')) ? 0.01 : $userLevel->amount;
        $orderData = [
            'order_no' => $outTradeNo,
            'order_name' => $orderName,//订单标题
            'user_id' => $userId,
            'goods_id' => $goodsId,
            'firm_type' => 100,//业务类型
            'pay_amount' => $payAmount,//付款金额，单位:元
            'pay_status' => 6000,
            'pay_way' => 1,
            'create_time' => time(),
        ];
        //创建订单
        $orderId = $this->orderRepository->insertGetId($orderData);
        if (0 < $orderId) {
            /*** 请填写以下配置信息 ***/
            $appid = config('pay.alipay.appid');  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
            $notifyUrl = config('pay.alipay.notify_url');     //付款成功后的异步回调地址
            $signType = 'RSA2';			//签名算法类型，支持RSA2和RSA，推荐使用RSA2
            //商户私钥
            $rsaPrivateKey= config('pay.alipay.rsa_private_key');
            /*** 配置结束 ***/
            $aliPay = new AlipayService();
            $aliPay->setAppid($appid);
            $aliPay->setNotifyUrl($notifyUrl);
            $aliPay->setRsaPrivateKey($rsaPrivateKey);
            $aliPay->setTotalFee($payAmount);
            $aliPay->setOutTradeNo($outTradeNo);
            $aliPay->setOrderName($orderName);
            $aliPay->signType($signType);
            $orderStr = $aliPay->getOrderStr();
            $errorRes = [
                'order_no' => $outTradeNo,
                'error_code' => '',
                'error_msg' => json_encode($orderStr),
                'api_type' => 12
            ];
            $this->threeApiErrorLogsRepository->create($errorRes);
            return $this->responseJson(0, ['pay_info' => $orderStr]);
        } else {
            return $this->responseJson(400);
        }
    }
}